package com.awccis.admin.controller;

import com.awccis.admin.model.config.ConfigBean;
import com.awccis.admin.model.order.BreakOrderBean;
import com.awccis.admin.model.order.OrderSimpleInfo;
import com.awccis.admin.service.AdminOrderService;
import com.awccis.common.pool.CustomerPool;
import com.awccis.common.pool.DriverPool;
import com.awccis.common.session.DriverSession;
import com.awccis.common.utils.Constants;
import com.awccis.common.utils.HttpRequestUtil;
import com.awccis.common.utils.JsonUtil;
import com.awccis.customer.model.order.OrderBean;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: txp
 * @date: 2018/5/19 on 下午8:15
 * @since: 1.0
 * @description:
 **/
@Controller
@RequestMapping(value = "/admin/order")
public class AdminOrderController {

    /**
     * 日志打印对象
     */
    private Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Resource
    AdminOrderService adminOrderService;

    /**
     * 获取所有简单订单信息
     *
     * @param hashMap {"AWCCIS_CODE":"1a5da935ac641f2c46d5096f08d0c40b15234072",
     *                "totalCount":-1,
     *                "startCount": 2,
     *                "limitCounts": 3，
     *                "requestType": "driver",
     *                "id": 2
     *                }
     * @return map
     */
    @RequestMapping(value = "/simpleOrderInfo", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Map<String, Object> simpleOrderInfo(@RequestBody HashMap<String, Object> hashMap) {
        logger.info("获取简单订单信息" + hashMap);
        Map map = new HashMap(2);

        String awccisCode = "AWCCIS_CODE";
        String totalCount = "totalCount";
        String startCount = "startCount";
        String limitCounts = "limitCounts";
        String requestType = "requestType";
        String id = "id";

        if (hashMap.get(awccisCode) == null || !Constants.AWCCIS_CODE.equals(hashMap.get(awccisCode).toString())) {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "code非法请求值！");
            return map;
        } else if (hashMap.get(startCount) == null || hashMap.get(limitCounts) == null) {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "限定值非法！");
            return map;
        }
        int counts = Integer.parseInt(hashMap.get(totalCount).toString());
        int resultCount = 0;


        List<OrderSimpleInfo> list = null;
        if (hashMap.get(requestType) == null || "".equals(hashMap.get(requestType).toString())) {
            list = adminOrderService.getAllSimpleOrderInfo(hashMap);
            //若传入的总数值不为-1则直接返回传入的值
            if (counts == -1) {
                resultCount = adminOrderService.getOrdersSumNumber();
            } else {
                resultCount = counts;
            }
        } else if ("driver".equals(hashMap.get(requestType)) || "customer".equals(hashMap.get(requestType))) {
            if (hashMap.get(id) != null && "driver".equals(hashMap.get(requestType))) {
                try {
                    Integer.parseInt(hashMap.get(id).toString());
                } catch (NumberFormatException e) {
                    logger.warn("请求获取订单时候，类型转换异常：" + e);
                    map.put(Constants.MAP_KEY_RESULT, false);
                    map.put(Constants.MAP_KEY_MESSAGE, "id请求值非法！");

                    return map;
                }
                list = adminOrderService.getDriverOrderById(hashMap);
                //若传入的总数值不为-1则直接返回传入的值
                if (counts == -1) {
                    resultCount = adminOrderService.getOrdersSumNumByDId(hashMap);
                } else {
                    resultCount = counts;
                }
            }
            if (hashMap.get(id) != null && "customer".equals(hashMap.get(requestType))) {
                list = adminOrderService.getCustomerOrderByPhone(hashMap);
                //若传入的总数值不为-1则直接返回传入的值
                if (counts == -1) {
                    resultCount = adminOrderService.getOrdersSumNumByCId(hashMap);
                } else {
                    resultCount = counts;
                }
            }
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "type请求非法！");
            return map;
        }


        if (list.size() > 0) {
            map.put(Constants.MAP_KEY_RESULT, true);
            map.put(Constants.MAP_KEY_MESSAGE, list);
            map.put(Constants.MAP_KEY_TOTAL_COUNT, resultCount);
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "当前还没有订单数据！");
        }

        return map;
    }


    /**
     * 通过订单Id查找订单
     *
     * @param hashMap {"AWCCIS_CODE":"1a5da935ac641f2c46d5096f08d0c40b15234072",
     *                "orderId": 22
     *                }
     * @return
     */
    @RequestMapping(value = "/orderDetailInfoById", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Map orderInfoByUserId(@RequestBody HashMap<String, Object> hashMap) {
        logger.info("通过订单id查询订单：" + hashMap);
        Map map = new HashMap(2);

        String awccisCode = "AWCCIS_CODE";
        String orderId = "orderId";
        if (hashMap.get(awccisCode) == null || !Constants.AWCCIS_CODE.equals(hashMap.get(awccisCode).toString())) {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "code非法请求值！");
            return map;
        }
        if (hashMap.get(orderId) != null) {
            int id = 0;
            try {
                id = Integer.parseInt(hashMap.get(orderId).toString());
            } catch (NumberFormatException e) {
                //e.printStackTrace();
                logger.warn("通过orderId查询订单时候，orderId非法：" + e);
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "orderId请求值非法！");
                return map;
            }
            OrderBean orderBean = adminOrderService.getOrderDetailInfoById(id);
            if (orderBean != null) {
                map.put(Constants.MAP_KEY_RESULT, true);
                map.put(Constants.MAP_KEY_MESSAGE, orderBean);
            } else {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "订单信息异常！");
            }
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "orderId请求值非法！");
            return map;
        }

        return map;
    }

    /**
     * 获取所有未完成订单
     *
     * @param hashMap hashMap {"AWCCIS_CODE":"1a5da935ac641f2c46d5096f08d0c40b15234072"}
     * @return map
     */
    @RequestMapping(value = "/getAllNoFinishOrder", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Map getAllNoFinishOrder(@RequestBody HashMap<String, String> hashMap) {
        logger.info("获取所有未完成订单：" + hashMap);

        Map map = new HashMap(2);

        String awccisCode = "AWCCIS_CODE";
        if (hashMap.get(awccisCode) == null || !Constants.AWCCIS_CODE.equals(hashMap.get(awccisCode).toString())) {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "code非法请求值！");
            return map;
        } else {
            List<OrderBean> list = adminOrderService.getAllNoFinishOrder();
            if (list.size() > 0) {
                map.put(Constants.MAP_KEY_RESULT, true);
                map.put(Constants.MAP_KEY_MESSAGE, list);
            } else {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "当前未有未完成订单！");
            }
        }

        return map;
    }

    /**
     * 根据司机提供的信息，查找当前订单数据信息
     *
     * @param hashMap {"driverNickName":23}
     * @return
     */
    @RequestMapping(value = "/getBreakOrder", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Map<String, Object> getBreakOrder(@RequestBody HashMap<String, Integer> hashMap) {
        logger.info("查找一个未完成订单信息：" + hashMap);
        System.out.println("查询未完成订单：" + hashMap);

        Map<String, Object> map = new HashMap<>();
        String nickName = "driverNickName";
        if (hashMap.get(nickName) != null) {
            OrderBean orderBean = null;
            try {
                orderBean = adminOrderService.getBreakOrder(DriverPool.getSessionByNickName(hashMap.get(nickName)).getDriverId());
            } catch (NullPointerException e) {
                logger.warn("查询故障订单时候司机不在线" + e);
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "司机未登录！");
                return map;
            }
            if (orderBean != null) {
                map.put(Constants.MAP_KEY_RESULT, true);
                map.put(Constants.MAP_KEY_MESSAGE, orderBean);
            } else {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "订单信息不存在！");
            }
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "请求参数非法");
        }

        return map;
    }

    /**
     * 选择可以推送订单的司机
     *
     * @param hashMap {"AWCCIS_CODE": }
     * @return {}
     */
    @RequestMapping(value = "/chooseDriver", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Map<String, Object> chooseDriver(@RequestBody HashMap<String, String> hashMap) {
        logger.info("获取可以接单的司机" + hashMap);

        Map<String, Object> map = new HashMap<>();
        String awccisCode = "AWCCIS_CODE";
        if (hashMap.get(awccisCode) != null && Constants.AWCCIS_CODE.equals(hashMap.get(awccisCode))) {
            List<DriverSession> list = adminOrderService.getDriverToSend();
            if (list.size() > 0) {
                map.put(Constants.MAP_KEY_RESULT, true);
                map.put(Constants.MAP_KEY_MESSAGE, list);
            } else {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "没有可选择的driver!");
            }
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "code非法请求值！");
        }
        return map;
    }

    /**
     * 订单转移
     *
     * @param hashMap {
     *                "oldOrderId":263,
     *                "newDriverNickName":55,
     *                "breakOrder":
     *                {
     *                "orderId":263,
     *                "breakInfo":"车轮左前胎爆胎",
     *                "breakLocation":"在葛关路位置",
     *                "breakTime":"2018-06-24"
     *                }
     *                }
     * @return {}
     */
    @RequestMapping(value = "/transferOrder", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Map<String, Object> transferOrder(@RequestBody HashMap<String, Object> hashMap) {
        logger.info("转移订单：" + hashMap);
        System.out.println("转移订单：" + hashMap);

        Map<String, Object> map = new HashMap<>();
        String id = "oldOrderId";
        String driverNickName = "newDriverNickName";
        String order = "breakOrder";
        if (hashMap.get(id) != null && hashMap.get(driverNickName) != null && hashMap.get(order) != null) {
             DriverSession driverSession = null;
            int oldOrderId = 0;
            int newDriverId = 0;
            try {
                oldOrderId = Integer.parseInt(hashMap.get(id).toString());
                driverSession = DriverPool.getSessionByNickName(Integer.parseInt(hashMap.get(driverNickName).toString())).Dclone();
                newDriverId = driverSession.getDriverId();
            } catch (NumberFormatException e) {
                logger.warn("转移订单提供oldOrderId类型转换异常:" + e);

                map.put(Constants.MAP_VALUE_ERROR, false);
                map.put(Constants.MAP_KEY_MESSAGE, "请求参数类型异常！");
                return map;
            } catch (NullPointerException e) {
                logger.warn("转移订单提供oldOrderId空指针异常:" + e);

                map.put(Constants.MAP_VALUE_ERROR, false);
                map.put(Constants.MAP_KEY_MESSAGE, "请求参数异常！请检查司机是否在线");
                return map;
            }
            BreakOrderBean breakOrderBean = JsonUtil.str2obj(hashMap.get(order).toString(), BreakOrderBean.class);
            OrderBean orderBean = adminOrderService.getOrderDetailInfoById(oldOrderId);
            orderBean.setDriverId(newDriverId);
            orderBean.setDriverName(driverSession.getDriverName());
            orderBean.setDriverNickName(driverSession.getDriverNickName());
            orderBean.setDriverPhone(driverSession.getDriverPhone());
            orderBean.setOrderParentId(oldOrderId);
            boolean result = adminOrderService.transferOrder(oldOrderId, orderBean, breakOrderBean);
            orderBean.setOrderId(orderBean.getOrderId());
            orderBean.setOrderOnPlaceLai(driverSession.getLat());
            orderBean.setOrderOnPlaceLong(driverSession.getLng());

            String param = "";
            JsonObject obj = null;
            String address = null;

            try {
                param = driverSession.getLat() + "," + driverSession.getLng();
                obj = JsonUtil.str2obj(HttpRequestUtil.sendGet(Constants.GET_NAME_BY_JING_WEI, param), JsonObject.class);
                address = obj.getAsJsonArray("results").get(0).getAsJsonObject().get("formatted_address").getAsString();
            } catch (Exception e) {
                logger.warn("获取当前故障位置名称出现异常：" + e);
                driverSession.setDistance(100000000.000);
            }

            orderBean.setOrderTravelOnPlace(address);
            map.put(Constants.MAP_KEY_RESULT, result);
            if (result) {
                DriverSession finalDriverSession = driverSession;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        int count = 0;
                        boolean cflag=false;
                        boolean dflag=false;
                        String cmsg = "sendMessage2customer:"+JsonUtil.json2str(finalDriverSession);
                        String dmsg = "sendMessage2driver:"+JsonUtil.json2str(orderBean);
                        System.out.println(cmsg);
                        System.out.println(dmsg);
                        while (!cflag || !dflag){
                            if(!cflag){
                                cflag = CustomerPool.sendMessageByPhone(orderBean.getCustomerPhone(),  cmsg);
                            }
                            if(!dflag){
                                dflag = DriverPool.sendMessageByNickName(finalDriverSession.getDriverNickName(),  dmsg);
                            }
                            try {
                                Thread.sleep(5000);
                                count++;
                                if (count >= 12) {
                                    break;
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                                break;
                            }
                        }
                    }
                }).start();
            } else {
                map.put(Constants.MAP_KEY_MESSAGE, "订单转移失败，请检查数据！");
            }
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "请求参数非法！");
        }

        return map;
    }

    /**
     * 获取系统参数信息
     *
     * @param hashMap {"AWCCIS_CODE":"1a5da935ac641f2c46d5096f08d0c40b15234072"}
     * @return
     */
    @RequestMapping(value = "/getConfig", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Map getConfig(@RequestBody HashMap<String, String> hashMap) {
        logger.info("获取系统参数信息：" + hashMap);
        Map map = new HashMap(2);

        String awccisCode = "AWCCIS_CODE";
        if (hashMap.get(awccisCode) == null || !Constants.AWCCIS_CODE.equals(hashMap.get(awccisCode))) {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "code非法请求值！");
            return map;
        } else {
            ConfigBean configBean = adminOrderService.getSystemInfo();
            if (configBean != null) {
                map.put(Constants.MAP_KEY_RESULT, true);
                map.put(Constants.MAP_KEY_MESSAGE, configBean);
            } else {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "系统参数有误！");
            }
        }
        return map;
    }

    /**
     * 更改系统参数
     *
     * @param configBean {}
     * @return {}
     */
    @RequestMapping(value = "/setConfig", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Map setConfig(@RequestBody ConfigBean configBean) {
        logger.info("更改系统参数：" + configBean.toString());

        Map map = new HashMap(2);
        if (configBean != null) {
            if (configBean.getRange() <= 0) {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "range非法请求值！");
                return map;
            }
            if (configBean.getRate() <= 0) {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "rate非法请求值！");
                return map;
            }
            if (configBean.getScore() <= 0) {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "score非法请求值！");
                return map;
            }
            if (configBean.getProportion() <= 0) {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "proportion非法请求值！");
                return map;
            }
            boolean result = adminOrderService.setSystemInfo(configBean);
            if (result) {
                map.put(Constants.MAP_KEY_RESULT, result);
                map.put(Constants.MAP_KEY_MESSAGE, "更改成功！");
            } else {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "更改失败！");
            }
        }
        return map;
    }

}
